from config import db
from datetime import datetime

Blog_comments = db.Table('blog_comments',
                         db.Column('Tweet_id', db.Integer, db.ForeignKey('tweet.id'), default=0, comment="博客的id"),
                         db.Column('content', db.String(255), default="", comment="评论"),
                         db.Column('user_id', db.Integer, db.ForeignKey('user.id'), default=0,
                                   comment="评论对应的用户"),
                         db.Column('parent_id', db.Integer, default=0, comment='评论恢复的ID'),
                         db.Column('create_time', db.DateTime, default=datetime.utcnow)
                         )


class Tweet(db.Model):
    __tablename__ = "tweet"
    __table_args__ = {'mysql_engine': 'InnoDB'}  # 设置表的存储引擎为InnoDB
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(128), comment="标题")
    body = db.Column(db.Text, comment="文章")
    text_body = db.Column(db.Text, comment="文章纯文本")
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    userid = db.Column(db.Integer, db.ForeignKey('user.id'))
    views = db.Column(db.Integer, default=0, comment="此博文的浏览量")

    def __repr__(self):
        return "T={},create_at={}".format(
            self.body, self.create_time
        )

    def blog_post(self):
        # pprint(type(data))
        data = Tweet.query.filter_by(id=self.id).first()
        data.views += 1  # 增加浏览量
        db.session.commit()

    # 热门推荐
    @staticmethod
    def popular_ten_data():
        # 推荐热门的10条数据
        popular_ten_data = Tweet.query.order_by(Tweet.views.desc(), Tweet.create_time.desc()).limit(10).all()

        for key, value in enumerate(popular_ten_data):
            num = key+1
            if key == 0:
                popular_ten_data[key].color = '<i class="layui-badge-rim layui-bg-red">1</i>'
            elif key == 1:
                popular_ten_data[key].color = '<i class="layui-badge-rim layui-bg-orange">2</i>'
            elif key == 2:
                popular_ten_data[key].color = '<i class="layui-badge-rim layui-bg-green">3</i>'
            else:
                popular_ten_data[key].color = '<i class="layui-badge-rim">'+str(num)+'</i>'

        return popular_ten_data


